import { request } from "@/utils/request";
import type { VxeGridProps } from "vxe-table";
import XEUtils from "xe-utils";

export default () => {
  // 表单配置
  const serveApiUrl = import.meta.env.VITE_API_URL;
  const userEmployee = ref([]);
  const getEmployee = async () => {
    return await request({
      url: `api/admin/user/employee`,
      method: "GET",
    });
  };
  const sumNum = (list: ReceiptItemModel[], field: string) => {
    let count = 0
    list.forEach(item => {
      count += Number(item[field])
    })
    return count
  }
  const countAmount = (row: ReceiptItemModel) => {
    let mount = row.score
    return mount
  }
  const countAllAmount = (data: ReceiptItemModel[]) => {
    let count = 0
    data.forEach(row => {
      count += countAmount(row)
    })
    return count
  }
  const footerMethod = ({ columns, data }) => {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计'
        }
        if (columnIndex === 5) {
          return `数量： 共 ${sumNum(data, 'score')}`
        } 
        return '-'
      })
    ]
  }
  const gridOptions = reactive<VxeGridProps>({
    footerMethod:footerMethod,
    border: true,
    stripe: true,
    loading: true,
    showFooter:true,
    showHeaderOverflow: true,
    showOverflow: true,
    keepSource: true,
    autoResize: true,
    columnConfig: {
      resizable: true,
    },
    expandConfig: {
      trigger: "row",
      showIcon: true,
      expandRowKeys: [1, 2],
      iconOpen: "vxe-icon--caret-bottom",
      iconClose: "vxe-icon--caret-top",
    },
    formConfig: {
      titleWidth: 80,
      titleAlign: "right",
      items: [
        {
          field: "created_at",
          title: "开始时间",
          span: 6,
          itemRender: {
            name: "$input",
            props: { placeholder: "模糊查询：【日：2024-12-12】" },
          },
        },
        {
          field: "updated_at",
          title: "结束时间",
          span: 6,
          itemRender: {
            name: "$input",
            props: { placeholder: "模糊查询：【日：2024-12-31】" },
          },
        },
        {
          field: "user_id",
          title: "员工",
          span: 8,
          itemRender: {
            name: "$select",
            props: {
              placeholder: "请选择员工",
              options: userEmployee.value,
            },
          },
        },
        {
          span: 24,
          align: "left",
          collapseNode: true,
          itemRender: {
            name: "$buttons",
            children: [
              {
                props: {
                  type: "submit",
                  content: "搜索",
                  status: "primary",
                },
              },
              { props: { type: "reset", content: "重置" } },
            ],
          },
        },
      ],
    },
    id: "full_edit_9999",
    rowConfig: {
      keyField: "#",
      isHover: true,
      useKey: true,
    },
    customConfig: {
      storage: true,
      checkMethod({ column }) {
        if (["name", "no"].includes(column.field)) {
          return false;
        }
        return true;
      },
    },
    printConfig: {
      columns: [{ field: "name" }],
    },
    sortConfig: {
      trigger: "cell",
      remote: true,
    },
    filterConfig: {
      remote: true,
    },
    pagerConfig: {
      enabled: true,
      pageSize: 10,
      pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
    },
    toolbarConfig: {
      buttons: [
        // {code: "insert_actived", name: "快捷新增", status: "primary"},
        // {code: "delete", name: "直接删除", status: "danger"},
        // {code: "mark_cancel", name: "删除/取消"},
        // {code: "save", name: "保存", status: "success"},
      ],
      refresh: true, // 显示刷新按钮
      import: false, // 显示导入按钮
      export: true, // 显示导出按钮
      print: true, // 显示打印按钮
      zoom: true, // 显示全屏按钮
      custom: true, // 显示自定义列按钮
    },
    proxyConfig: {
      seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
      sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
      filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
      form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
      props: {
        // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
        result: "data", // 配置响应结果列表字段
        total: "total", // 配置响应结果总页数字段
      },
      // 只接收Promise，具体实现自由发挥
      ajax: {
        // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
        query: async ({ page, sorts, filters, form }) => {
          const queryParams: any = Object.assign({}, form);
          // 处理排序条件
          const firstSort = sorts[0];
          if (firstSort) {
            queryParams.sort = firstSort.field;
            queryParams.order = firstSort.order;
          }
          // 处理筛选条件
          filters.forEach(({ field, values }) => {
            queryParams[field] = values.join(",");
          });
          let options = await getEmployee();
          userEmployee.value = options.map(item=>{
            return {
              label:item.name,
              value:item.id
            }
          })
          return request({
            url: `api/admin/record?pageSize=${page.pageSize}&currentPage=${
              page.currentPage
            }&${XEUtils.serialize(queryParams)}`,
            method: "GET",
            isReturnResult: false,
          }).then((response) => {
            gridOptions.loading = false;
            return response;
          });
        },
      },
    },
    columns: [
      { field: "id", title: "id" },
      // 配置日期选择器
      {
        field: "repair",
        title: "报修单",
        sortable: true,
        slots: {
          default: "repair",
        },
      },
      {
        field: "user",
        title: "维修工",
        slots: {
          default: "user",
        },
      },
      {
        field: "user_id",
        title: "维修工id",
        sortable: true,
      },
      {
        field: "kind",
        title: "车型",
        slots: {
          default: "kind",
        },
      },
      {
        field: "score",
        title: "工时",
      },
    ],
    importConfig: {},
    exportConfig: {},
    checkboxConfig: {
      labelField: "ID",
      checkStrictly: true,
    },
    editRules: {
      name: [
        { required: true, message: "必填" },
        { min: 3, max: 50, message: "名称长度在 3 到 50 个字符" },
      ],
      no: [{ required: true, message: "必填" }],
    },
    editConfig: {
      trigger: "click",
      mode: "row",
      showStatus: true,
      showUpdateStatus: true,
      showInsertStatus: true,
      autoClear: true,
    },
  });

  return {
    gridOptions,
    userEmployee
  };
};
